/**
 * 公告资料维护 - 编辑页面
 * @author miaoyl
 * @date 2018/01/03 16:00
 */
define(function () {

    var self,
        app = win.app,
        doc = document,
        vueData = {
            count: 0,
            imgs: g_ctxPath + 'upload/imgs',
            img: '',
            imgList: [],
            fileList: [],
            files: g_ctxPath + 'upload/files',
            list1: [],
            list2: [],
            isAdd: false,
            gwdh002: false,
            form: '',
            rules: {
                GWDH001: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWDH002: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWDH004: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWDH006: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWDH007: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ],
                GWDHACTI: [
                    {required: true, message: '不可为空', trigger: 'blur'}
                ]
            },
            selectOptions: {
                gwdh002: app.datas_('sys_notice_gwdh002'),
                sys_y_n: app.datas_('sys_y_n')
            }
        },
        cols = [[
            {field: 'GWDHO001', type: 'checkbox', title: '选择'}
            , {field: 'GWDHO002', width: 80, title: '对象编号'}
            , {field: 'GWDHO003', width: 80, title: '对象说明'}
        ]],
        callObj, table, userTable, listData = null,index,
        layedit
    ;

    var NoticeEdit = app.Module.extend({
        init: function () {
            self = this;
            self._super({
                _tag: 'notice_edit',
                _loadTplsFull: [
                    // {dom: 'common_open_multi_org', tpl: 'common/_open_multi_org'},
                    // {dom: 'common_open_multi_kh', tpl: 'common/_open_multi_kh'},
                    // {dom: 'common_open_multi_xsqd', tpl: 'common/_open_multi_xsqd'},
                    // {dom: 'common_open_sys_user', tpl: 'common/_open_sys_user'},
                    {dom: 'common_open_window', tpl: 'common/_open_window'}

                ]
            }, win);
        },

        initEdit:function () {
            layui.use(['layedit'], function(){
                layedit = layui.layedit;
                layedit.set({
                    uploadImage: {
                        url: g_ctxPath + 'upload/imgsEdit' //接口url
                        , type: 'post' //默认post
                    }
                });

                index =  layedit.build('demo'); //建立编辑器
                layedit.setContent(index, vueData.form.GWDH007);
            });
        },

        initTable: function () {
            layui.use(['table'], function () {
                table = layui.table;
                userTable = table.render({
                    elem: app.getByid(doc, 'user_table'),
                    id: 'user_table',
                    cols: cols,
                    data: listData,
                    page: false,
                    height: 300,
                    where: ''
                });

            });
        },

        tableReload: function (data) {
            userTable.reload({
                data: data
            });
        },

        edit: function (data, list1, list2) {
            app.ajax({
                xurl: 'sys/notice/edit',
                xdata: {data: data, list1: list1, list2: list2},
                loading: true,
                toJsonStr: true,
                okmsg: '公告资料修改成功',
                cb: function (result) {
                    if (result.ok) {
                        //同步更新缓存对应的值
                        app.pageModule('notice').reloadTableCurr();
                        vueData.address = '';
                        vueData.img = '';
                        vueData.fileList = [];
                        vueData.imgList = [];
                        self._closeTpl();
                    }
                }
            });
        },
        add: function (data, list1, list2) {
            app.ajax({
                xurl: 'sys/notice/addData',
                xdata: {data: data, list1: list1, list2: list2},
                loading: true,
                toJsonStr: true,
                okmsg: '公告资料信息保存成功',
                cb: function (result) {
                    if (result.ok) {
                        app.pageModule('notice').reloadTableCurr();
                        vueData.address = '';
                        vueData.img = '';
                        vueData.fileList = [];
                        vueData.imgList = [];
                        self._closeTpl();
                    }
                }
            });
        },
        _call: function (obj) {
            vueData.address = '';
            vueData.img = '';
            vueData.fileList = [];
            vueData.imgList = [];
            vueData.list2 = [];
            vueData.count = 0;
            if (obj.is_add) {
                vueData.isAdd = true;
                vueData.gwdh002 = false;
                app.ajax({
                    xurl: 'sys/notice/getAddData',
                    cb: function (result) {
                        if (result.ok) {
                            app.extendUpLow({
                                target: vueData.form,
                                res: {
                                    GWDHDOCNO: result.data.data.GWDHDOCNO,
                                    GWDH004: result.data.data.GWDH004,
                                    GWDH004_NAME: result.data.data.GWDH004_NAME,
                                    GWDH005: result.data.data.GWDH005,
                                    GWDHACTI: 'Y'
                                },
                                reset: true
                            });
                            listData = [];
                            self.tableReload(listData);
                        }
                    }
                });
                app.extendUpLow({
                    target: vueData.form,
                    res: {},
                    reset: true
                });
            } else {
                vueData.isAdd = false;
                callObj = obj;

                if (callObj.data.GWDH008 != undefined) {
                    if (callObj.data.GWDH008.length > 0) {
                        vueData.img = callObj.data.GWDH008;
                        vueData.imgList.push({
                            name: callObj.data.GWDH008, url: '/wissun-smfile/' + callObj.data.GWDH008
                        })
                    }
                }
                if (callObj.data.GWDHE != undefined) {
                    if (callObj.data.GWDHE.length > 0) {
                        vueData.address = callObj.data.GWDHE;
                        var data = callObj.data.GWDHE.split(',');
                        for (var i = 0; i < data.length; i++) {
                            vueData.fileList.push({
                                name: data[i], url: '/wissun-smfile/' + data[i]
                            })
                            vueData.list2.push({
                                GWDHE002: data[i]
                            })
                        }
                    }
                }
                app.ajax({
                    xurl: 'sys/notice/getGwdhoData',
                    xdata: {GWDHODOCNO: callObj.data.GWDHDOCNO},
                    cb: function (result) {
                        if (result.ok) {
                            listData = result.data.data;
                            self.tableReload(listData);
                            if (listData.length > 0) {
                                vueData.gwdh002 = true;
                            }
                        }
                    }
                });
                listData = [];
                self.tableReload(listData);
                app.extendUpLow({
                    target: vueData.form,
                    res: callObj.data,
                    reset: true
                });
            }
            self.initEdit();
        },
        _ready: function () {
            vueData.form = app.fields_(['gwdh'], {GWDH004_NAME: null});
            var vue = new Vue({
                el: '#notice_edit',
                data: vueData,
                methods: {
                    cancel: function () {
                        self._closeTpl();
                    },
                    sure: function () {
                        vueData.form.GWDH007 = layedit.getContent(index);
                        this.$refs['form'].validate(function (valid) {
                            if (valid) {
                                vueData.form.GWDHE = '';
                                for (var i = 0; i < vueData.list2.length; i++) {
                                    if (i == 0) {
                                        vueData.form.GWDHE = vueData.list2[i].GWDHE002;
                                    } else {
                                        vueData.form.GWDHE = vueData.form.GWDHE + ',' + vueData.list2[i].GWDHE002;
                                    }
                                }
                                vueData.list2.forEach(function (v) {
                                    vue.$refs.upload2.uploadFiles.removeByMap({
                                        name: v.GWDHE002
                                    });
                                });
                                var list = userTable.getDatas();
                                vueData.list1 = list;
                                if (list.length == 0) {
                                    app.showWarning('发布对象不可为空!');
                                    return;
                                }
                                if (vueData.form.GWDH006 < vueData.form.GWDH005) {
                                    app.showWarning('失效日期不可小于发布日期!');
                                    return;
                                }
                                if (vueData.form.GWDH007.length > 8000) {
                                    app.showWarning('公告内容长度不能大于8000!');
                                    return;
                                }
                                if (vueData.isAdd) {
                                    var flag = true;
                                    if (vue.$refs.upload1.uploadFiles.length > 0) {
                                        flag = false;
                                        vue.$refs.upload1.submit();
                                    } else {
                                        if (vue.$refs.upload2.uploadFiles.length > 0) {
                                            flag = false;
                                            vue.$refs.upload2.submit();
                                        }
                                    }
                                    if (flag) {
                                        var data = [];
                                        data.push(vueData.form);
                                        self.add(data, vueData.list1, vueData.list2);
                                    }
                                } else {
                                    var flag = true;
                                    if (vue.$refs.upload1.uploadFiles.length > 0) {
                                        flag = false;
                                        if (vueData.img != '') {
                                            if (vueData.img != vueData.form.GWDH008) {
                                                vue.$refs.upload1.submit();
                                            } else {
                                                if (vue.$refs.upload2.uploadFiles.length > 0) {
                                                    flag = false;
                                                    vue.$refs.upload2.submit();
                                                } else {
                                                    flag = true;
                                                }
                                            }
                                        } else {
                                            vue.$refs.upload1.submit();
                                        }
                                    } else {
                                        if (vue.$refs.upload2.uploadFiles.length > 0) {
                                            flag = false;
                                            vue.$refs.upload2.submit();
                                        } else {
                                            flag = true;
                                        }
                                    }
                                    if (flag) {
                                        var data = [];
                                        data.push(vueData.form);
                                        self.edit(data, vueData.list1, vueData.list2);
                                    }
                                }
                            }
                        });
                    },
                    openUser: function () {
                        self._openTplFull({
                            tag: 'common_open_window',
                            tagData: {
                                config:{
                                    method:'q_sysuser_id',
                                    columnList:[
                                        {label: '交易对象编号', prop: 'ID', width: '150'},
                                        {label: '交易对象名称', prop: 'NAME', width: '150'}
                                    ]
                                },
                                cb: function (data) {
                                    vueData.form.GWDH004 = data.ID;
                                    vueData.form.GWDH004_NAME = data.NAME;
                                }
                            },
                            index: 0,
                            openOpts: {
                                title: '选择人员信息',
                                area: ['600px', '550px']
                            }
                        });
                    },
                    addData: function () {
                        if (vueData.form.GWDH002 != '' && vueData.form.GWDH002 != null) {
                            if (vueData.form.GWDH002 == 1) {
                                var list = userTable.getDatas();
                                var count = list.length + 1;
                                var keyArray=[];
                                for(var i =0;i<list.length;i++){
                                    keyArray.push(
                                        list[i]['GWDHO002']
                                    );
                                }
                                var keyArrayStr=keyArray.join(',');
                                self._openTplFull({
                                    tag: 'common_open_window',
                                    tagData: {
                                        multiple:true,
                                        config:{
                                            method:'q_sysorg_id',
                                            columnList: [
                                                {label: '组织编号', prop: 'ID', width: '150'},
                                                {label: '组织名称', prop: 'NAME', width: '150'}
                                            ],
                                            dataList:[],
                                            key:'ID',
                                            searchParam:{
                                                keyArrayStr:keyArrayStr
                                            }
                                        },
                                        cb: function (data) {
                                            for (var i = 0; i < data.length; i++) {
                                                list.push({
                                                    'GWDHO001': count + i,
                                                    'GWDHO002': data[i].ID,
                                                    'GWDHO003': data[i].NAME
                                                });
                                            }
                                            self.tableReload(list);
                                            if (list.length > 0) {
                                                vueData.gwdh002 = true;
                                            }
                                        }
                                    },
                                    index: 0,
                                    openOpts: {
                                        title: '选择组织信息',
                                        area: ['600px', '550px']
                                    }
                                });
                            }
                            else if (vueData.form.GWDH002 == 2) {
                                var list = userTable.getDatas();
                                var count = list.length + 1;
                                var keyArray=[];
                                for(var i =0;i<list.length;i++){
                                    keyArray.push(
                                        list[i]['GWDHO002']
                                    );
                                }
                                var keyArrayStr=keyArray.join(',');
                                self._openTplFull({
                                    tag: 'common_open_window',
                                    tagData: {
                                        multiple:true,
                                        config:{
                                            method:'q_gwae001',
                                            columnList: [
                                                {label: '销售渠道编号', prop: 'GWAE001', width: '150'},
                                                {label: '说明', prop: 'GWAEL003', width: '150'},
                                                {label: '助记码', prop: 'GWAEL004', width: '150'}
                                            ],
                                            dataList:[],
                                            key:'GWAE001',
                                            searchParam: {
                                                keyArrayStr:keyArrayStr
                                            }
                                        },
                                        cb: function (data) {
                                            for (var i = 0; i < data.length; i++) {
                                                list.push({
                                                    'GWDHO001': count + i,
                                                    'GWDHO002': data[i].GWAE001,
                                                    'GWDHO003': data[i].GWAEL003
                                                });
                                            }
                                            self.tableReload(list);
                                            if (list.length > 0) {
                                                vueData.gwdh002 = true;
                                            }
                                        }
                                    },
                                    index: 0,
                                    openOpts: {
                                        title: '选择渠道信息',
                                        area: ['600px', '550px']
                                    }
                                });
                            }
                            else if (vueData.form.GWDH002 == 3) {
                                var list = userTable.getDatas();
                                var count = list.length + 1;
                                var keyArray=[];
                                for(var i =0;i<list.length;i++){
                                    keyArray.push(
                                        list[i]['GWDHO002']
                                    );
                                }
                                var keyArrayStr=keyArray.join(',');
                                self._openTplFull({
                                    tag: 'common_open_window',
                                    tagData: {
                                        multiple:true,
                                        config:{
                                            method:'q_gwak001',
                                            columnList: [
                                                {label:'客户编号',prop:'GWAK001', width: 150},
                                                {label:'客户简称',prop:'GWAKL003', width: 150},
                                                {label:'客户全称',prop:'GWAKL004', width: 150}
                                            ],
                                            dataList:[],
                                            key:'GWAK001',
                                            searchParam: {
                                                keyArrayStr:keyArrayStr
                                            }
                                        },
                                        cb: function (data) {
                                            for (var i = 0; i < data.length; i++) {
                                                list.push({
                                                    'GWDHO001': count + i,
                                                    'GWDHO002': data[i].GWAK001,
                                                    'GWDHO003': data[i].GWAKL004
                                                });
                                            }
                                            self.tableReload(list);
                                            if (list.length > 0) {
                                                vueData.gwdh002 = true;
                                            }
                                        }
                                    },
                                    index: 0,
                                    openOpts: {
                                        title: '选择客户信息',
                                        area: ['600px', '550px']
                                    }
                                });
                            }
                        } else {
                            app.showWarning('请先选择公告类型');
                        }
                    },
                    del: function () {
                        var list = userTable.getDatas();
                        var checkStatus = table.checkStatus('user_table');
                        if (checkStatus.data.length > 0) {
                            checkStatus.data.forEach(function (v) {
                                list.removeByMap({
                                    GWDHO001: v.GWDHO001
                                });
                            });
                            if (list.length == 0) {
                                vueData.gwdh002 = false;
                            }
                            self.tableReload(list);
                        }
                    },
                    beforeUploadImg: function (file) {
                        const isJPG = (file.type === 'image/png' || file.type === 'image/jpeg'
                        || file.type === 'image/gif');
                        const isLt2M = file.size / 1024 / 1024 < 2;
                        if (!isJPG) {
                            this.$message.error("上传图片只能是 JPG|PNG|GIF 格式!");
                        }
                        if (!isLt2M) {
                            this.$message.error("上传图片大小不能超过 2MB!");
                        }

                        return isJPG && isLt2M;
                    },
                    successUploadImg: function (response) {
                        if (response.code == 200) {
                            vue.$message.success('图片上传成功');
                            vueData.form.GWDH008 = response.data[0].name;
                            if (vue.$refs.upload2.uploadFiles.length > 0) {
                                if (vueData.address != '') {
                                    if (vueData.address != vueData.form.GWDHE) {
                                        vue.$refs.upload2.submit();
                                    } else {
                                        if (vueData.isAdd) {
                                            var data = [];
                                            data.push(vueData.form);
                                            self.add(data, vueData.list1, vueData.list2);
                                        } else {
                                            var data = [];
                                            data.push(vueData.form);
                                            var data = vueData.form.GWDHE.split(',');
                                            for (var i = 0; i < data.length; i++) {
                                                vueData.list2.push({GWDHE002: data[i]});
                                            }
                                            self.edit(data, vueData.list1, vueData.list2);
                                        }
                                    }
                                } else {
                                    vue.$refs.upload2.submit();
                                }
                            } else {
                                if (vueData.isAdd) {
                                    var data = [];
                                    data.push(vueData.form);
                                    self.add(data, vueData.list1, vueData.list2);
                                } else {
                                    var data = [];
                                    data.push(vueData.form);
                                    self.edit(data, vueData.list1, vueData.list2);
                                }
                            }
                            vue.$refs.upload1.clearFiles();
                        }
                    },
                    beforeUploadFiles: function (file) {
                        const isJPG = (file.type === 'application/pdf'
                        || file.type === 'application/msword' || file.type === 'application/vnd.ms-excel'
                        || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                        || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
                        || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
                        const isLt2M = file.size / 1024 / 1024 < 5;
                        if (!isJPG) {
                            this.$message.error('文件格式不对');
                        }
                        if (!isLt2M) {
                            this.$message.error('文件大小不对');
                        }
                        return isJPG && isLt2M;
                    },
                    successUploadFiles: function (response) {
                        if (response.code == 200) {
                            vue.$message.success('文件上传成功');
                            if (vueData.form.GWDHE == '' || vueData.form.GWDHE == null) {
                                vueData.form.GWDHE = response.data[0].name;
                            } else {
                                vueData.form.GWDHE = vueData.form.GWDHE + ',' + response.data[0].name;
                            }
                            vueData.count++;
                            if (vueData.count == vue.$refs.upload2.uploadFiles.length) {
                                vueData.list2 = [];
                                var data2 = vueData.form.GWDHE.split(',');
                                for (var i = 0; i < data2.length; i++) {
                                    vueData.list2.push({
                                        GWDHE002: data2[i]
                                    })
                                }
                                if (vueData.isAdd) {
                                    var data = [];
                                    data.push(vueData.form);
                                    self.add(data, vueData.list1, vueData.list2);
                                } else {
                                    var data = [];
                                    data.push(vueData.form);
                                    self.edit(data, vueData.list1, vueData.list2);
                                }
                                vue.$refs.upload2.clearFiles();
                            }

                        }
                    },
                    handleJpgRemove: function (file, fileList) {
                        vueData.form.GWDH008 = "";
                    },
                    handleFileRemove: function (file, fileList) {
                        if (!vueData.isAdd) {
                            vueData.list2.removeByMap({
                                GWDHE002: file.name
                            });
                            file = '';
                        }
                    },
                    handleImgPreview: function (file) {
                        var img_infor = "<img src='" + '/wissun-smfile/' + file.name + "' />";
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 1,
                            area: '516px',
                            skin: 'layui-layer-nobg', //没有背景色
                            shadeClose: true,
                            content: img_infor
                        });
                    },
                    handleFilePreview: function (file) {
                        window.open('/wissun-smfile/' + file.name);
                    },
                    handleExceed: function (files, fileList) {
                        this.$message.warning("当前只允许选择一个文件，如果需要选择新的文件，请先删除之前的文件!");
                    },
                    handleExceedImg: function (files, fileList) {
                        this.$message.warning("当前只允许选择一个图片，如果需要选择新的图片，请先删除之前的图片!");
                    }
                },
                watch: {},
                created: function () {
                    self._setEleIsReady('notice_edit');
                }
            });
            self.initTable();
        },
        _lazy: function () {
            this._super();
        }
    });

    return new NoticeEdit();

});
